package com.xgs.web.controller.common;

import java.awt.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import com.xgs.common.config.XgsWebConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xgs.common.constant.CacheConstants;
import com.xgs.common.constant.Constants;
import com.xgs.common.core.domain.AjaxResult;
import com.xgs.common.core.redis.RedisCache;
import com.xgs.common.utils.uuid.IdUtils;
import com.xgs.system.service.ISysConfigService;

/**
 * 验证码操作处理
 *
 * @author xgs
 */
@RestController
public class CaptchaController
{
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;
    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException, FontFormatException {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        // 生成验证码
        Captcha captcha;
        if("math".equals(XgsWebConfig.getCaptchaType())) {
            captcha = new ArithmeticCaptcha(115, 42);
        }else if("chinese".equals(XgsWebConfig.getCaptchaType())) {
            captcha = new ChineseCaptcha(115, 42);
        }else {
            captcha = new SpecCaptcha(115, 42, 4);
            captcha.setFont(Captcha.FONT_2);
            captcha.setCharType(Captcha.TYPE_ONLY_LOWER);
        }
        String code = captcha.text();
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        ajax.put("uuid", uuid);
        ajax.put("img", captcha.toBase64());
        return ajax;
    }
}